package cn.ibizlab.util.ad;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.ibizlab.core.ad.service.SysOrganizationService;
import cn.ibizlab.util.errors.BadRequestAlertException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;

@Component
public class SysOrganizationTreeUtil {

    @Autowired
    @Lazy
    SysOrganizationService sysOrganizationService;

    /**
     * 查询当前单位的下级子单位id集合
     * @param orgId
     * @return
     */
    public List<String> getSubOrgIdsByOrgId(String orgId){

        if(ObjectUtils.isEmpty(orgId))
            return Collections.emptyList();

        //子单位id集合
        List<String> subOrgIds = null;

        //构造顶层组织树
        List<TreeNode<String>> orgNodes = CollUtil.newArrayList();
        sysOrganizationService.list().forEach(organization -> orgNodes.add(new TreeNode<>(organization.getId(), organization.getParentId(), organization.getOrganizationName(), 5)));

        if(!ObjectUtils.isEmpty(orgNodes)){
            List<Tree<String>> rootOrgTree = TreeUtil.build(orgNodes, null);
            if(ObjectUtils.isEmpty(rootOrgTree)){
                throw new BadRequestAlertException("构造组织树失败，请确认是否顶层机构的parentId是否为null" ,"","");
            }

            //在顶层单位树中查找当前orgId树节点
            for(Tree<String> orgTree : rootOrgTree){
                Tree<String> orgNode = orgTree.getNode(orgId);
                //获取当前orgId节点的所有子单位ids
                if(orgNode != null){
                    subOrgIds = getSubOrgIds(orgNode);
                    break;
                }
            }
        }
        return subOrgIds;
    }

    /**
     * 递归查找当前树所有下级节点ids
     * @param orgNode
     * @return
     */
    protected List<String> getSubOrgIds(Tree<String> orgNode){

        List<Tree<String>> subOrgNodes = orgNode.getChildren();
        if(ObjectUtils.isEmpty(subOrgNodes))
            return Collections.emptyList();

        List<String> subOrgIds = CollUtil.newArrayList();
        for (Tree<String> subOrgNode : subOrgNodes) {

            if(ObjectUtils.isEmpty(subOrgNode.getId()))
                continue;

            subOrgIds.add(subOrgNode.getId());

            //递归遍历查询子节点
            if(!ObjectUtils.isEmpty(subOrgNode.getChildren())){
                List<String> subOrgIds2 = getSubOrgIds(subOrgNode);
                if(!ObjectUtils.isEmpty(subOrgIds2))
                    subOrgIds.addAll(subOrgIds2);
            }
        }
        return subOrgIds;
    }
}
